package spider.util;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import spider.NovelSiteEnum;

import java.io.*;
import java.net.URI;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public final class NovelSpiderUtil {
    private static final Map< NovelSiteEnum, Map< String, String > > CONTEXT_MAP = new HashMap<>();

    static {
        init();  // 类执行前执行初始方法
    }

    private NovelSpiderUtil() {
    }

    private static void init() {
        SAXReader reader = new SAXReader();  //加载xml文件
        try {
//            Document doc = reader.read( new File( "src/conf/Spider_Rule.xml" ) );//获取文件路径
            URL url = NovelSpiderUtil.class.getClassLoader().getResource( "conf/Spider_Rule.xml" );
            URI uri = new URI( url.toString() );
            Document doc = reader.read( new File( uri.getPath() ) );//获取文件路径
            Element root = doc.getRootElement();//得到根结点  sites
            List< Element > sites = root.elements( "site" );
            for ( Element site : sites ) {
                List< Element > subs = site.elements();
                Map< String, String > subMap = new HashMap<>();
                for ( Element sub : subs ) {
                    String name = sub.getName();
                    String text = sub.getTextTrim();
                    subMap.put( name, text );
                }
                CONTEXT_MAP.put( NovelSiteEnum.getNovelSiteEnumByUrl( subMap.get( "url" ) ), subMap );
            }

        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    /**
     * 拿到对应网站的解析规则
     *
     * @param novelSiteEnum 枚举类
     * @return 返回解析规则
     */
    public static Map< String, String > getContext( NovelSiteEnum novelSiteEnum ) {
        return CONTEXT_MAP.get( novelSiteEnum );
    }


    /**
     * 多个文件合并,按文件名排序
     *
     * @param path           基础目录,该目录下的所有文本文件
     * @param merger2File    合并成可以为null  合并在path/merger.txt
     * @param deleteThisFile 是否删除文件
     */
    public static void multiFileMerger( String path, String merger2File, boolean deleteThisFile ) {
        if ( merger2File == null ) merger2File = path + "/merger.txt";
        File[] files = new File( path ).listFiles( new FilenameFilter() {
            @Override
            public boolean accept( File dir, String name ) {
                return name.endsWith( ".txt" );
            }
        } );
        Arrays.sort( files, new Comparator< File >() {
            @Override
            public int compare( File o1, File o2 ) {
                String name1 = o1.getName().split( "-" )[0];
                String name2 = o2.getName().split( "-" )[0];
                return Integer.valueOf( name1 ) - Integer.valueOf( name2 );
            }
        } );

        PrintWriter out = null;
        try {
            out = new PrintWriter( new File( merger2File ), "UTF-8" );
        } catch ( FileNotFoundException | UnsupportedEncodingException e ) {
            e.printStackTrace();
        }
        for ( File file : files ) {
            try (
                    BufferedReader bufr = new BufferedReader( new InputStreamReader( new FileInputStream( file ), "UTF-8" ) );
            ) {
                String line = null;
                while ( ( line = bufr.readLine() ) != null ) {
                    out.println( line );
                }
                bufr.close();
                if ( deleteThisFile ) {
                    file.delete();
                }
            } catch ( Exception e ) {
                throw new RuntimeException( "合并失败" );
            }
        }
        out.close();
    }

    /**
     * @param status 传入状态信息 连载,完本
     * @return 连载1  完本2
     */
    public static int getNovelStatus( String status ) {
        if ( status.contains( "连载" ) ) return 1;
        else if ( status.contains( "完" ) ) return 2;
        else throw new RuntimeException( "不知道什么状态" + status );
    }

    /**
     * 格式化日期
     *
     * @param dateStr 日期字符串
     * @param pattern
     * @return 日期对象
     * @throws ParseException
     */
    public static Date getDate( String dateStr, String pattern ) throws ParseException {
        if ( pattern.equals( "MM-dd" ) ) {
            pattern = "yyyy-MM-dd";
            dateStr = getDateField( Calendar.YEAR )+"-" +dateStr;
        }
        SimpleDateFormat sdf = new SimpleDateFormat( pattern );
        return sdf.parse( dateStr );
    }

    public static String getDateField( int field ) {
        Calendar cal = new GregorianCalendar();
        return cal.get( field ) + "";
    }
}
